<template>
  <div>
    <ZgEdit
      v-if="hasView"
      ref="dialog"
      :view="view"
      :title="title"
      :showTitle="showTitle"
      :layout="layout"
      :columns="columns"
      :formulas="formulas"
      validUrl=""
      :saveUrl="`/zg-autoform/zxb/table/data/update/${formCode}`"
      @ok="$emit('ok')">
    </ZgEdit>
  </div>
</template>
<script>
export default {
  props: {
    formCode: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      view: { width: '60%', top: '5%', title: '修改数据' },
      hasView: false,
      title: '',
      showTitle: false,
      layout: { 视图边距: 10, 标签宽度: 120, 标签对齐: 'right', 左右间距: 10, 上下间距: 10 },
      columns: [],
      formulas: [
        { triggerMode: '初始化时', name: '公式1', content: 'console.log("init");' },
        { triggerMode: '数据变化时', name: '公式2', content: 'console.log("update");' },
        { triggerMode: '提交时', name: '公式3', content: 'console.log("submit");' }
      ]
    }
  },
  watch: {
    formCode () {
      this.fetchView()
    }
  },
  mounted () {
    this.fetchView()
  },
  methods: {
    open (json) {
      if (!this.hasView) {
        this.$error({ title: `没有找到视图数据` })
        return
      }
      this.$refs.dialog.open(json)
    },
    fetchView () {
      this.hasView = false
      if (!this.formCode || this.formCode.length === 0) {
        return
      }
      this.$http.get('/zg-autoform/zxb/form/view', {
        formCode: this.formCode,
        viewType: 'update'
      }, viewArr => {
        if (viewArr && viewArr.length > 0) {
          this.layout = JSON.parse(viewArr[0].layout)
          this.$http.get('/zg-autoform/zxb/view/findById', {
            id: viewArr[0].id
          }, viewInfo => {
            this.title = viewInfo.title
            this.showTitle = viewInfo.showTitle
            // 先排序
            const arr = viewInfo.columns.sort((a, b) => {
              return a.sort - b.sort
            })
            // 转化默认值和extra
            this.columns = arr.map(t => {
              return Object.assign({}, t, {
                extra: JSON.parse(t.extra),
                defaultVal: this.generateDefaultVal(t)
              })
            })
            this.hasView = true
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
